/*
  testNumPages.c - Linux Page Replacement Investigation
  Ben Marks, Chris Lekas

  Determines the number of pages that can be allocated and accessed
  before swapping occurs.

 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <linux/pgfltstats.h>

#include "common.h"

#define PAGESIZE 4080

/* A very large array to store the allocated page pointers */
char * big[400000];


/*
  Allocate and access memory until we start causing major page faults.
 */
int main() {
  
  int i, j;
  char * tmp; 

  struct pf_info_struct before;

  while (1) { // Break out once major page faults start ocurring
    
    if ( pgfltstats( getpid(), PGFLTSTAT_PROC, &before ) ) {
      perror("pgfltstats");
    }
    if ( before.major > 30 ) {
      break;
    }

    // Allocate memory
    tmp = (char*)malloc(PAGESIZE);
    if ( ! tmp ) {
      printf("Ran out of memory ... ");
      perror("malloc");
      exit(1);
    }
    
    // Access allocated memory
    big[i] = tmp;
    for ( j = 0; j < i; j ++ ) {
      big[j][0] = 'a';
    }

    // Keep track of number of allocated pages
    i++;
  }
  
  // Report results
  printf("Num\t%d\n", i );

}
